<template>
  <div class="form-template">
    <div class="page-header">
      <h1>表单字段模板</h1>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新增字段
        </el-button>
        <el-button @click="showImportDialog = true">
          <el-icon><Upload /></el-icon>
          导入模板
        </el-button>
        <el-button @click="exportTemplates">
          <el-icon><Download /></el-icon>
          导出模板
        </el-button>
      </div>
    </div>

    <div class="template-container">
      <div class="template-header">
        <div class="filter-section">
          <el-input
            v-model="searchText"
            placeholder="搜索字段名称或标签"
            style="width: 300px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="filterCategory" placeholder="选择分类" clearable style="width: 200px; margin-left: 10px">
            <el-option
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
          <el-select v-model="filterType" placeholder="选择字段类型" clearable style="width: 200px; margin-left: 10px">
            <el-option
              v-for="type in fieldTypes"
              :key="type.type"
              :label="type.label"
              :value="type.type"
            />
          </el-select>
          <el-switch
            v-model="showActiveOnly"
            active-text="仅显示启用"
            inactive-text="显示全部"
            style="margin-left: 20px"
          />
        </div>
        
        <div class="action-section">
          <el-button @click="showSortDialog = true">
            <el-icon><Sort /></el-icon>
            批量排序
          </el-button>
          <el-button @click="previewForm">
            <el-icon><View /></el-icon>
            预览表单
          </el-button>
        </div>
      </div>

      <div class="template-categories">
        <div v-for="category in filteredCategories" :key="category" class="category-section">
          <div class="category-header">
            <h3>{{ category }}</h3>
            <div class="category-actions">
              <el-button size="small" @click="addFieldToCategory(category)">添加字段</el-button>
              <el-button size="small" @click="sortCategoryFields(category)">排序</el-button>
            </div>
          </div>
          
          <div class="fields-grid">
            <div
              v-for="field in getFieldsByCategory(category)"
              :key="field.id"
              class="field-card"
              :class="{ 'field-inactive': !field.is_active }"
            >
              <div class="field-header">
                <div class="field-info">
                  <h4>{{ field.field_label }}</h4>
                  <span class="field-name">{{ field.field_name }}</span>
                </div>
                <div class="field-actions">
                  <el-button size="small" @click="previewField(field)">
                    <el-icon><View /></el-icon>
                  </el-button>
                  <el-button size="small" @click="editField(field)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button size="small" @click="copyField(field)">
                    <el-icon><CopyDocument /></el-icon>
                  </el-button>
                  <el-button size="small" type="danger" @click="deleteField(field)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
              
              <div class="field-content">
                <div class="field-type">
                  <el-tag :type="getFieldTypeColor(field.field_type)" size="small">
                    {{ getFieldTypeLabel(field.field_type) }}
                  </el-tag>
                  <el-tag v-if="field.is_required" type="danger" size="small">必填</el-tag>
                  <el-tag v-if="!field.is_active" type="info" size="small">禁用</el-tag>
                </div>
                
                <div v-if="field.placeholder" class="field-placeholder">
                  <span>占位符：{{ field.placeholder }}</span>
                </div>
                
                <div v-if="field.help_text" class="field-help">
                  <span>帮助文本：{{ field.help_text }}</span>
                </div>
                
                <div v-if="field.default_value" class="field-default">
                  <span>默认值：{{ field.default_value }}</span>
                </div>
                
                <div v-if="hasOptions(field)" class="field-options">
                  <span>选项：{{ getOptionsPreview(field.field_options) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建/编辑字段对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingField ? '编辑字段' : '新增字段'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="fieldForm" :rules="fieldRules" ref="fieldFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="字段名称" prop="field_name">
              <el-input v-model="fieldForm.field_name" placeholder="英文字段名，如：user_name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段标签" prop="field_label">
              <el-input v-model="fieldForm.field_label" placeholder="显示标签，如：用户姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="字段类型" prop="field_type">
              <el-select v-model="fieldForm.field_type" style="width: 100%" @change="onFieldTypeChange">
                <el-option
                  v-for="type in fieldTypes"
                  :key="type.type"
                  :label="type.label"
                  :value="type.type"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-input v-model="fieldForm.category" placeholder="字段分类" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="占位符">
              <el-input v-model="fieldForm.placeholder" placeholder="输入提示文本" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="默认值">
              <el-input v-model="fieldForm.default_value" placeholder="默认值" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="帮助文本">
          <el-input v-model="fieldForm.help_text" type="textarea" :rows="2" placeholder="字段说明" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="必填">
              <el-switch v-model="fieldForm.is_required" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="启用">
              <el-switch v-model="fieldForm.is_active" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序">
              <el-input-number v-model="fieldForm.sort_order" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 字段选项配置 -->
        <el-form-item v-if="supportsOptions" label="字段选项">
          <div class="options-editor">
            <div v-for="(option, index) in fieldOptions" :key="index" class="option-item">
              <el-input v-model="option.label" placeholder="显示文本" style="width: 200px" />
              <el-input v-model="option.value" placeholder="选项值" style="width: 200px; margin-left: 10px" />
              <el-switch v-model="option.disabled" inactive-text="启用" active-text="禁用" style="margin-left: 10px" />
              <el-button type="danger" size="small" @click="removeOption(index)" style="margin-left: 10px">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-button @click="addOption" style="margin-top: 10px">
              <el-icon><Plus /></el-icon>
              添加选项
            </el-button>
          </div>
        </el-form-item>
        
        <!-- 验证规则配置 -->
        <el-form-item label="验证规则">
          <div class="validation-editor">
            <div v-for="(rule, index) in validationRules" :key="index" class="rule-item">
              <el-select v-model="rule.type" placeholder="规则类型" style="width: 150px">
                <el-option label="必填" value="required" />
                <el-option label="最小长度" value="min" />
                <el-option label="最大长度" value="max" />
                <el-option label="正则表达式" value="pattern" />
                <el-option label="邮箱" value="email" />
                <el-option label="手机号" value="phone" />
                <el-option label="网址" value="url" />
              </el-select>
              <el-input v-model="rule.value" placeholder="规则值" style="width: 150px; margin-left: 10px" />
              <el-input v-model="rule.message" placeholder="错误提示" style="width: 200px; margin-left: 10px" />
              <el-button type="danger" size="small" @click="removeRule(index)" style="margin-left: 10px">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-button @click="addRule" style="margin-top: 10px">
              <el-icon><Plus /></el-icon>
              添加规则
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      
      <!-- 字段预览 -->
      <div class="field-preview">
        <h4>字段预览</h4>
        <div class="preview-container" v-html="fieldPreviewHtml"></div>
      </div>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button @click="validateField">验证配置</el-button>
        <el-button type="primary" @click="saveField">保存</el-button>
      </template>
    </el-dialog>

    <!-- 字段预览对话框 -->
    <el-dialog v-model="showPreviewDialog" title="字段预览" width="600px">
      <div v-if="previewingField" class="field-preview-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="字段名称">{{ previewingField.field_name }}</el-descriptions-item>
          <el-descriptions-item label="字段标签">{{ previewingField.field_label }}</el-descriptions-item>
          <el-descriptions-item label="字段类型">{{ getFieldTypeLabel(previewingField.field_type) }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ previewingField.category }}</el-descriptions-item>
          <el-descriptions-item label="必填">{{ previewingField.is_required ? '是' : '否' }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ previewingField.is_active ? '启用' : '禁用' }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="preview-render">
          <h4>渲染效果</h4>
          <div class="render-container" v-html="previewRenderHtml"></div>
        </div>
      </div>
    </el-dialog>

    <!-- 表单预览对话框 -->
    <el-dialog v-model="showFormPreviewDialog" title="表单预览" width="800px">
      <div class="form-preview">
        <el-form label-width="120px">
          <div v-for="category in categories" :key="category" class="form-category">
            <h4>{{ category }}</h4>
            <div v-for="field in getFieldsByCategory(category).filter(f => f.is_active)" :key="field.id">
              <!-- 这里会根据字段类型渲染不同的表单控件 -->
              <el-form-item :label="field.field_label" :required="field.is_required">
                <component :is="getFieldComponent(field)" v-bind="getFieldProps(field)" />
                <div v-if="field.help_text" class="field-help-text">{{ field.help_text }}</div>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog v-model="showImportDialog" title="导入模板" width="500px">
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        :show-file-list="false"
        accept=".json,.xlsx,.csv"
        drag
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 JSON、Excel、CSV 格式文件
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="showImportDialog = false">取消</el-button>
        <el-button type="primary" @click="importTemplates" :disabled="!importFile">导入</el-button>
      </template>
    </el-dialog>

    <!-- 排序对话框 -->
    <el-dialog v-model="showSortDialog" title="批量排序" width="600px">
      <div class="sort-container">
        <el-table :data="sortFields" stripe>
          <el-table-column prop="field_label" label="字段标签" />
          <el-table-column prop="field_name" label="字段名称" />
          <el-table-column prop="category" label="分类" />
          <el-table-column label="排序" width="120">
            <template #default="{ row }">
              <el-input-number v-model="row.sort_order" :min="0" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row, $index }">
              <el-button size="small" @click="moveFieldUp($index)" :disabled="$index === 0">
                <el-icon><ArrowUp /></el-icon>
              </el-button>
              <el-button size="small" @click="moveFieldDown($index)" :disabled="$index === sortFields.length - 1">
                <el-icon><ArrowDown /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="showSortDialog = false">取消</el-button>
        <el-button type="primary" @click="saveSortOrder">保存排序</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Sort, View, Edit, Delete, CopyDocument, Upload, Download,
  ArrowUp, ArrowDown, UploadFilled
} from '@element-plus/icons-vue'
import {
  formTemplatesApi,
  type FormFieldTemplate,
  type FieldOption,
  type ValidationRule
} from '@/api'

// 响应式数据
const fields = ref<FormFieldTemplate[]>([])
const searchText = ref('')
const filterCategory = ref('')
const filterType = ref('')
const showActiveOnly = ref(true)
const categories = ref<string[]>([])
const fieldTypes = ref<any[]>([])
const showCreateDialog = ref(false)
const showPreviewDialog = ref(false)
const showFormPreviewDialog = ref(false)
const showImportDialog = ref(false)
const showSortDialog = ref(false)
const editingField = ref<FormFieldTemplate | null>(null)
const previewingField = ref<FormFieldTemplate | null>(null)
const importFile = ref<File | null>(null)
const fieldPreviewHtml = ref('')
const previewRenderHtml = ref('')

// 排序相关
const sortFields = ref<FormFieldTemplate[]>([])

// 表单数据
const fieldForm = reactive({
  field_name: '',
  field_label: '',
  field_type: 'text',
  field_options: '',
  default_value: '',
  is_required: false,
  is_active: true,
  validation_rules: '',
  placeholder: '',
  help_text: '',
  sort_order: 0,
  category: ''
})

// 字段选项和验证规则
const fieldOptions = ref<FieldOption[]>([])
const validationRules = ref<ValidationRule[]>([])

// 表单验证规则
const fieldRules = {
  field_name: [
    { required: true, message: '请输入字段名称', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '字段名称必须以字母开头，只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  field_label: [{ required: true, message: '请输入字段标签', trigger: 'blur' }],
  field_type: [{ required: true, message: '请选择字段类型', trigger: 'change' }],
  category: [{ required: true, message: '请输入分类', trigger: 'blur' }]
}

// 计算属性
const filteredCategories = computed(() => {
  let categoryList = categories.value
  
  if (filterCategory.value) {
    categoryList = categoryList.filter(cat => cat === filterCategory.value)
  }
  
  return categoryList
})

const supportsOptions = computed(() => {
  return ['select', 'radio', 'checkbox'].includes(fieldForm.field_type)
})

// 方法
const loadFields = async () => {
  try {
    const response = await formTemplatesApi.getFormFieldTemplates()
    fields.value = response.data
    
    // 提取分类列表
    const categorySet = new Set(fields.value.map(f => f.category))
    categories.value = Array.from(categorySet)
  } catch (error) {
    ElMessage.error('加载字段模板失败')
  }
}

const loadFieldTypes = async () => {
  try {
    const response = await formTemplatesApi.getFieldTypes()
    // 后端返回的数据格式是 {field_types: [...]}，需要转换为前端期望的格式
    const backendFieldTypes = response.data.field_types || []
    fieldTypes.value = backendFieldTypes.map(item => ({
      type: item.value,
      label: item.label,
      supports_options: ['select', 'radio', 'checkbox'].includes(item.value)
    }))
  } catch (error) {
    console.error('加载字段类型失败', error)
    // 使用默认字段类型
    fieldTypes.value = [
      { type: 'text', label: '文本', supports_options: false },
      { type: 'textarea', label: '多行文本', supports_options: false },
      { type: 'number', label: '数字', supports_options: false },
      { type: 'date', label: '日期', supports_options: false },
      { type: 'datetime', label: '日期时间', supports_options: false },
      { type: 'select', label: '下拉选择', supports_options: true },
      { type: 'radio', label: '单选', supports_options: true },
      { type: 'checkbox', label: '多选', supports_options: true },
      { type: 'file', label: '文件上传', supports_options: false },
      { type: 'email', label: '邮箱', supports_options: false },
      { type: 'phone', label: '手机号', supports_options: false },
      { type: 'url', label: '网址', supports_options: false }
    ]
  }
}

const getFieldsByCategory = (category: string) => {
  let categoryFields = fields.value.filter(f => f.category === category)
  
  if (searchText.value) {
    categoryFields = categoryFields.filter(f => 
      f.field_name.toLowerCase().includes(searchText.value.toLowerCase()) ||
      f.field_label.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }
  
  if (filterType.value) {
    categoryFields = categoryFields.filter(f => f.field_type === filterType.value)
  }
  
  if (showActiveOnly.value) {
    categoryFields = categoryFields.filter(f => f.is_active)
  }
  
  return categoryFields.sort((a, b) => a.sort_order - b.sort_order)
}

const getFieldTypeLabel = (type: string) => {
  const fieldType = fieldTypes.value.find(t => t.type === type)
  return fieldType ? fieldType.label : type
}

const getFieldTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    text: 'info',
    textarea: 'info',
    number: 'success',
    date: 'warning',
    datetime: 'warning',
    select: 'primary',
    radio: 'primary',
    checkbox: 'primary',
    file: 'danger'
  }
  return colors[type] || 'info'
}

const hasOptions = (field: FormFieldTemplate) => {
  return ['select', 'radio', 'checkbox'].includes(field.field_type) && field.field_options
}

const getOptionsPreview = (optionsStr: string) => {
  try {
    const options = JSON.parse(optionsStr)
    return options.map((opt: FieldOption) => opt.label).join(', ')
  } catch {
    return '配置错误'
  }
}

const addFieldToCategory = (category: string) => {
  editingField.value = null
  resetFieldForm()
  fieldForm.category = category
  showCreateDialog.value = true
}

const editField = (field: FormFieldTemplate) => {
  editingField.value = field
  Object.assign(fieldForm, field)
  
  // 解析选项和验证规则
  try {
    fieldOptions.value = field.field_options ? JSON.parse(field.field_options) : []
  } catch {
    fieldOptions.value = []
  }
  
  try {
    validationRules.value = field.validation_rules ? JSON.parse(field.validation_rules) : []
  } catch {
    validationRules.value = []
  }
  
  showCreateDialog.value = true
}

const copyField = async (field: FormFieldTemplate) => {
  try {
    const newName = `${field.field_name}_copy`
    await formTemplatesApi.copyFormFieldTemplate(field.id, newName)
    ElMessage.success('复制成功')
    loadFields()
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const deleteField = async (field: FormFieldTemplate) => {
  try {
    await ElMessageBox.confirm('确定要删除这个字段模板吗？', '确认删除', {
      type: 'warning'
    })
    
    await formTemplatesApi.deleteFormFieldTemplate(field.id)
    ElMessage.success('删除成功')
    loadFields()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const previewField = async (field: FormFieldTemplate) => {
  previewingField.value = field
  
  try {
    const response = await formTemplatesApi.previewField(field)
    previewRenderHtml.value = response.data.html
  } catch (error) {
    previewRenderHtml.value = '<div>预览生成失败</div>'
  }
  
  showPreviewDialog.value = true
}

const onFieldTypeChange = () => {
  // 当字段类型改变时，清空不适用的配置
  if (!supportsOptions.value) {
    fieldOptions.value = []
  }
}

const addOption = () => {
  fieldOptions.value.push({
    label: '',
    value: '',
    disabled: false
  })
}

const removeOption = (index: number) => {
  fieldOptions.value.splice(index, 1)
}

const addRule = () => {
  validationRules.value.push({
    type: 'required',
    value: '',
    message: ''
  })
}

const removeRule = (index: number) => {
  validationRules.value.splice(index, 1)
}

const validateField = async () => {
  try {
    const config = {
      ...fieldForm,
      field_options: JSON.stringify(fieldOptions.value),
      validation_rules: JSON.stringify(validationRules.value)
    }
    
    const response = await formTemplatesApi.validateFieldConfig(config)
    
    if (response.data.isValid) {
      ElMessage.success('字段配置验证通过')
    } else {
      ElMessage.error(`验证失败：${response.data.errors.join(', ')}`)
    }
  } catch (error) {
    ElMessage.error('验证失败')
  }
}

const saveField = async () => {
  try {
    const config = {
      ...fieldForm,
      field_options: fieldOptions.value.length > 0 ? JSON.stringify(fieldOptions.value) : '',
      validation_rules: validationRules.value.length > 0 ? JSON.stringify(validationRules.value) : ''
    }
    
    if (editingField.value) {
      await formTemplatesApi.updateFormFieldTemplate(editingField.value.id, config)
      ElMessage.success('更新成功')
    } else {
      await formTemplatesApi.createFormFieldTemplate(config)
      ElMessage.success('创建成功')
    }
    
    showCreateDialog.value = false
    editingField.value = null
    resetFieldForm()
    loadFields()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const resetFieldForm = () => {
  Object.assign(fieldForm, {
    field_name: '',
    field_label: '',
    field_type: 'text',
    field_options: '',
    default_value: '',
    is_required: false,
    is_active: true,
    validation_rules: '',
    placeholder: '',
    help_text: '',
    sort_order: 0,
    category: ''
  })
  fieldOptions.value = []
  validationRules.value = []
}

const sortCategoryFields = (category: string) => {
  sortFields.value = getFieldsByCategory(category)
  showSortDialog.value = true
}

const moveFieldUp = (index: number) => {
  if (index > 0) {
    const temp = sortFields.value[index]
    sortFields.value[index] = sortFields.value[index - 1]
    sortFields.value[index - 1] = temp
    
    // 更新排序值
    sortFields.value.forEach((field, idx) => {
      field.sort_order = idx
    })
  }
}

const moveFieldDown = (index: number) => {
  if (index < sortFields.value.length - 1) {
    const temp = sortFields.value[index]
    sortFields.value[index] = sortFields.value[index + 1]
    sortFields.value[index + 1] = temp
    
    // 更新排序值
    sortFields.value.forEach((field, idx) => {
      field.sort_order = idx
    })
  }
}

const saveSortOrder = async () => {
  try {
    const updates = sortFields.value.map((field, index) => ({
      id: field.id,
      sort_order: index
    }))
    
    await formTemplatesApi.updateFieldsOrder(updates)
    ElMessage.success('排序保存成功')
    showSortDialog.value = false
    loadFields()
  } catch (error) {
    ElMessage.error('保存排序失败')
  }
}

const previewForm = () => {
  showFormPreviewDialog.value = true
}

const getFieldComponent = (field: FormFieldTemplate) => {
  // 根据字段类型返回对应的组件名
  const componentMap: Record<string, string> = {
    text: 'el-input',
    textarea: 'el-input',
    number: 'el-input-number',
    date: 'el-date-picker',
    datetime: 'el-date-picker',
    select: 'el-select',
    radio: 'el-radio-group',
    checkbox: 'el-checkbox-group',
    file: 'el-upload'
  }
  return componentMap[field.field_type] || 'el-input'
}

const getFieldProps = (field: FormFieldTemplate) => {
  // 根据字段类型返回对应的属性
  const baseProps: any = {
    placeholder: field.placeholder
  }
  
  if (field.field_type === 'textarea') {
    baseProps.type = 'textarea'
    baseProps.rows = 3
  }
  
  if (field.field_type === 'datetime') {
    baseProps.type = 'datetime'
  }
  
  return baseProps
}

const exportTemplates = async () => {
  try {
    const response = await formTemplatesApi.exportFieldTemplates(filterCategory.value)
    
    // 创建下载链接
    const blob = new Blob([response.data], { type: 'application/json' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `form_templates_${new Date().getTime()}.json`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

const handleFileChange = (file: any) => {
  importFile.value = file.raw
}

const importTemplates = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  try {
    const response = await formTemplatesApi.importFieldTemplates(importFile.value)
    
    ElMessage.success(`导入成功：${response.data.imported} 个模板，跳过 ${response.data.skipped} 个`)
    
    if (response.data.errors.length > 0) {
      ElMessage.warning(`部分导入失败：${response.data.errors.join(', ')}`)
    }
    
    showImportDialog.value = false
    importFile.value = null
    loadFields()
  } catch (error) {
    ElMessage.error('导入失败')
  }
}

// 监听字段表单变化，实时预览
watch(
  () => [fieldForm, fieldOptions.value, validationRules.value],
  async () => {
    if (showCreateDialog.value) {
      try {
        const config = {
          ...fieldForm,
          field_options: JSON.stringify(fieldOptions.value),
          validation_rules: JSON.stringify(validationRules.value)
        }
        
        const response = await formTemplatesApi.previewField(config)
        fieldPreviewHtml.value = response.data.html
      } catch {
        fieldPreviewHtml.value = '<div>预览生成中...</div>'
      }
    }
  },
  { deep: true }
)

// 生命周期
onMounted(() => {
  loadFields()
  loadFieldTypes()
})
</script>

<style scoped>
.form-template {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.template-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.filter-section {
  display: flex;
  align-items: center;
}

.action-section {
  display: flex;
  gap: 10px;
}

.template-categories {
  margin-top: 20px;
}

.category-section {
  margin-bottom: 30px;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.category-header h3 {
  margin: 0;
  color: #409eff;
}

.category-actions {
  display: flex;
  gap: 10px;
}

.fields-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.field-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 15px;
  background: #fafafa;
  transition: all 0.3s;
}

.field-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.field-card.field-inactive {
  opacity: 0.6;
  background: #f5f5f5;
}

.field-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.field-info h4 {
  margin: 0 0 5px 0;
  color: #303133;
}

.field-name {
  font-size: 12px;
  color: #909399;
  font-family: monospace;
}

.field-actions {
  display: flex;
  gap: 5px;
  opacity: 0;
  transition: opacity 0.3s;
}

.field-card:hover .field-actions {
  opacity: 1;
}

.field-content {
  font-size: 14px;
  color: #606266;
}

.field-type {
  display: flex;
  gap: 5px;
  margin-bottom: 8px;
}

.field-placeholder,
.field-help,
.field-default,
.field-options {
  margin-bottom: 5px;
  font-size: 12px;
  color: #909399;
}

.options-editor,
.validation-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  background: #fafafa;
}

.option-item,
.rule-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.field-preview {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.field-preview h4 {
  margin-bottom: 10px;
  color: #409eff;
}

.preview-container,
.render-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background: white;
  min-height: 60px;
}

.field-preview-detail {
  margin-top: 10px;
}

.preview-render {
  margin-top: 20px;
}

.preview-render h4 {
  margin-bottom: 10px;
  color: #409eff;
}

.form-preview {
  margin-top: 10px;
}

.form-category {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.form-category h4 {
  margin-bottom: 15px;
  color: #409eff;
}

.field-help-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.sort-container {
  margin-top: 10px;
}
</style>